package com.school.test.util;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;

import java.io.File;
import java.util.HashMap;
import java.util.Map;


public class QRCodeGenerator {
    public static void main(String[] args) {
        String text = "https://www.baidu.com";
        int width = 300;
        int height = 300;

        try {
            // 设置二维码参数
            Map<EncodeHintType, Object> hints = new HashMap<>();
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            hints.put(EncodeHintType.MARGIN, 1);

            // 生成二维码矩阵
            BitMatrix matrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height, hints);

            // 将二维码矩阵写入文件
            MatrixToImageWriter.writeToFile(matrix, "png", new File("qrcode.png"));

            System.out.println("二维码已生成");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
